package com.njrsrc.android.tasks;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.njrsrc.android.bean.NewsInfo;
import com.njrsrc.android.bean.UserInfo;
import com.njrsrc.common.utils.Helpers;
import com.njrsrc.common.utils.MsgID;

public class NewsTask extends AsyncTask<Object, Integer, Void> {
	private String url;
	private Handler mHandler;
	private UserInfo userInfo;
	private ArrayList<NewsInfo> newsList;

	@Override
	protected Void doInBackground(Object... params) {
		if (params.length < 4) {
			return null;
		}
		mHandler = (Handler) params[0];
		url = (String) params[1];
		userInfo = (UserInfo) params[2];
		newsList = (ArrayList<NewsInfo>) params[3];
		JSONObject jsonObject = Helpers.getJSONArrayByGet(url);
		Message msg = mHandler.obtainMessage();
		try {
			if(jsonObject == null)
			{
				msg.what = MsgID.NEWS_QUERY_ERROR;
			}
			else if (jsonObject.toString().contains("error_code")) {
				// 返回错误
				userInfo.setError_code(jsonObject.getString("error_code"));
				userInfo.setError_message(jsonObject.getString("error_message"));
				msg.what = MsgID.NEWS_QUERY_FAIL;
			} else {
				msg.what = MsgID.NEWS_QUERY_SUCCESS;
				JSONArray jobFairArray = jsonObject.getJSONArray("news");
				for (int i = 0; i < jobFairArray.length(); i++) {
					NewsInfo newsInfo = new NewsInfo();
					JSONObject jsonObjectItem = (JSONObject) jobFairArray.opt(i);
					newsInfo.setNews_id(jsonObjectItem.getString("news_id"));
					newsInfo.setTitle(jsonObjectItem.getString("title"));
					newsInfo.setSubtitle(jsonObjectItem.getString("subtitle"));
					newsInfo.setPublished_at(jsonObjectItem.getString("published_at"));
					newsInfo.setUrl(jsonObjectItem.getString("url"));
					newsInfo.setClick_count(jsonObjectItem.getString("click_count"));
					// 下面都一样
					newsList.add(newsInfo);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mHandler.sendMessage(msg);
		return null;
	}
}